/**
 * 简易的事件处理器，用于发送延时事件
 */
class EventHandler {
    constructor() {
        this.events = {}
    }

    /**
     * 是否包含事件
     */
    hasEvent(event) {
        if (!this.validateEvent(event)) return false

        return this.getEvent(event)
    }

    /**
     * 移除事件
     */
    removeEvent(event) {
        if (!this.validateEvent(event)) return

        const id = this.getEvent(event)
        if (id) {
            clearTimeout(id)
            this.deleteEvent(event)
        }
    }

    /**
     * 发送延时事件
     */
    sendTimingEvent(event, delay, handler) {
        if (!this.validateEvent(event)) return

        const id = setTimeout(() => {
            if (handler) handler()
            this.deleteEvent(event)
        }, delay)
        this.events[event] = id
    }

    getEvent(event) {
        return this.events[event]
    }

    deleteEvent(event) {
        if (this.getEvent(event)) {
            delete this.events[event]
        }
    }

    validateEvent(event) {
        return event && typeof event == 'string'
    }
}

export default EventHandler